package com.atguigu.gmall.realtime.app.dim;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.func.DimSinkFunction;
import com.atguigu.gmall.realtime.app.func.TableProcessFunction;
import com.atguigu.gmall.realtime.beans.TableProcess;
import com.atguigu.gmall.realtime.common.GmallConfig;
import com.atguigu.gmall.realtime.utils.HbaseUtil;
import com.atguigu.gmall.realtime.utils.KafkaUtil;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import com.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.hadoop.hbase.client.Connection;

import java.util.Properties;

/**
 * @author Felix
 * @date 2023/7/4
 * Dim层维度处理类
 * 需要启动的进程
 *      zk、kafka、maxwell、hdfs、hbase、DimApp
 * 开发流程
 *      基本环境准备
 *      检查点相关设置
 *      从kafka主题中读取数据
 *      对流中数据类型进行转换并进行简单的ETL清洗     jsonStr->jsonObj
 *      ~~~~~~~~~~~~~~~~~~~~~~~~~~~主流~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *      使用FlinkCDC到配置表中读取配置信息
 *      将读取到的配置信息封装为TableProcess对象
 *      根据配置信息提前在Habse中建表
 *      ~~~~~~~~~~~~~~~~~~~~~~~~~~~配置流~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *      将配置流进行广播---broadcast(广播状态描述器)
 *      将主流和广播流进行关联---connect
 *      对关联之后的数据进行处理---process
 *      class TableProcessFunction extends BroadcastProcessFunction{
 *          open: 将配置信息预加载到configMap中
 *          processElement:处理主流业务数据
 *              获取广播状态
 *              获取处理的业务数据库表的名称
 *              根据表名到广播状态以及configMap中获取对应的配置信息
 *              如果能够获取的到，说明是维度数据，写到下游
 *                  过滤掉不需要传递的属性
 *                  补充type操作类型
 *                  补充配置信息
 *          processBroadcastElement:处理广播流配置数据
 *              op='d':从广播状态以及configMap中，将对应的配置信息删除掉
 *              op!='d':将对象的配置信息放到广播状态以及configMap中
 *
 *      }
 *      将流中的维度数据写到Hbase表中
 *          class DimSinkFunction extends RichSinkFunction{
 *              invoke{
 *                  type="delete"
 *                      从Hbase表中将数据删除
 *                  type!="delete"
 *                      将数据put到Hbase表中
 *              }
 *          }
 * 执行流程(以向业务数据库品牌表中添加xy品牌为例)
 *      当DimApp程序启动的时候，会将配置表中的配置信息加载到configMap以及广播状态中
 *      当向品牌表中添加一条数据后
 *      binlog会记录品牌表的变化
 *      maxwell从binlog获取变化数据,并将变化数据封装为json格式字符串发送到kafka的topic_db主题中
 *      DimApp从topic_db主题中读取数据
 *      根据广播状态中以及configMap中的配置信息判断当前处理的数据是不是维度
 *      如果是维度的话，发送到下游，输出到Hbase
 */
public class DimApp {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备
        //1.1 指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(4);
        /*//TODO 2.检查点相关的设置
        //2.1 开启检查点
        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
        //2.2 设置检查点超时时间
        env.getCheckpointConfig().setCheckpointTimeout(60000L);
        //2.3 设置job取消之后检查点是否保留
        env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        //2.4 设置两个检查点之间最小的时间间隔
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
        //2.5 设置重启策略
        // env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3,3000L));
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30),Time.seconds(3)));
        //2.6 设置状态后端
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        //2.7 设置操作Hadoop的用户
        System.setProperty("HADOOP_USER_NAME","atguigu");*/

        //TODO 3.从kafka主题中读取数据
        //3.1 声明消费的主题以及消费者组
        String topic = "topic_db";
        String groupId = "dim_app_group";
        //3.2 创建消费者对象
        KafkaSource<String> kafkaSource = KafkaUtil.getKafkaSource(topic, groupId);
        //3.3 消费数据 封装为流
        DataStreamSource<String> kafkaStrDS
            = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "Kafka Source");

        //TODO 4.对流中数据进行类型转换 jsonStr->jsonObj    并进行简单的ETL
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.process(
            new ProcessFunction<String, JSONObject>() {
                @Override
                public void processElement(String jsonStr, Context ctx, Collector<JSONObject> out) throws Exception {
                    try {
                        JSONObject jsonObj = JSON.parseObject(jsonStr);
                        String type = jsonObj.getString("type");
                        if (!"bootstrap-start".equals(type) && !"bootstrap-complete".equals(type)) {
                            out.collect(jsonObj);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        );
        // jsonObjDS.print(">>>");

        //TODO 5.使用FlinkCDC读取配置表数据
        //5.1 创建MySqlSource
        Properties props = new Properties();
        props.setProperty("useSSL", "false");
        MySqlSource<String> mySqlSource = MySqlSource.<String>builder()
            .hostname("hadoop102")
            .port(3306)
            .databaseList("gmall0201_config") // set captured database
            .tableList("gmall0201_config.table_process_dim") // set captured table
            .username("root")
            .password("123456")
            .jdbcProperties(props)
            .serverTimeZone("Asia/Shanghai")
            .deserializer(new JsonDebeziumDeserializationSchema())
            .startupOptions(StartupOptions.initial())
            .build();

        //5.2 读取数据 封装为流
        DataStreamSource<String> mysqlDS
            = env.fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "mysql_source");
        // mysqlDS.print(">>>");

        //5.3 将流中数据进行类型转换 jsonStr->配置实体类对象
        SingleOutputStreamOperator<TableProcess> tableProcessDS = mysqlDS.map(
            new MapFunction<String, TableProcess>() {
                @Override
                public TableProcess map(String jsonStr) throws Exception {
                    JSONObject jsonObj = JSON.parseObject(jsonStr);
                    String op = jsonObj.getString("op");
                    TableProcess tableProcess = null;
                    if ("d".equals(op)) {
                        tableProcess = jsonObj.getObject("before", TableProcess.class);
                    } else {
                        tableProcess = jsonObj.getObject("after", TableProcess.class);
                    }
                    tableProcess.setOp(op);
                    return tableProcess;
                }
            }
        );

        // tableProcessDS.print(">>>");

        //TODO 6.根据配置表中的配置信息提前在Hbase中将维度表创建出来
        tableProcessDS = tableProcessDS.process(
            new ProcessFunction<TableProcess, TableProcess>() {
                private Connection conn;

                @Override
                public void open(Configuration parameters) throws Exception {
                    conn = HbaseUtil.getConnection();
                }

                @Override
                public void close() throws Exception {
                   HbaseUtil.closeConnection(conn);
                }

                @Override
                public void processElement(TableProcess tableProcess, Context ctx, Collector<TableProcess> out) throws Exception {
                    //获取对配置表进行的操作类型
                    String op = tableProcess.getOp();
                    //获取表名
                    String sinkTable = tableProcess.getSinkTable();
                    //获取列族
                    String sinkFamily = tableProcess.getSinkFamily();
                    if("r".equals(op)||"c".equals(op)){
                        //建表
                        HbaseUtil.createTable(conn, GmallConfig.HBASE_NAMESPACE,sinkTable,sinkFamily.split(","));
                    }else if("d".equals(op)){
                        //删表
                        HbaseUtil.dropTable(conn,GmallConfig.HBASE_NAMESPACE,sinkTable);
                    }else{
                        //先删表
                        HbaseUtil.dropTable(conn,GmallConfig.HBASE_NAMESPACE,sinkTable);
                        //再建表
                        HbaseUtil.createTable(conn, GmallConfig.HBASE_NAMESPACE,sinkTable,sinkFamily.split(","));
                    }
                    out.collect(tableProcess);
                }
            }
        );
        //TODO 7.将配置流进行广播---广播流
        MapStateDescriptor<String, TableProcess> mapStateDescriptor
            = new MapStateDescriptor<String, TableProcess>("mapStateDescriptor",String.class,TableProcess.class);

        BroadcastStream<TableProcess> broadcastDS = tableProcessDS.broadcast(mapStateDescriptor);

        //TODO 8.将主流和广播流进行关联---connect
        BroadcastConnectedStream<JSONObject, TableProcess> connectDS
            = jsonObjDS.connect(broadcastDS);

        //TODO 9.对关联之后的数据进行处理---得到维度数据
        SingleOutputStreamOperator<JSONObject> dimDS = connectDS.process(
            new TableProcessFunction(mapStateDescriptor)
        );

        //TODO 10.将维度数据写到Hbase表中
        dimDS.print(">>>>");
        dimDS.addSink(
            new DimSinkFunction()
        );

        env.execute();
    }
}